<template>
    <div>
        <section class="todoapp">
      <!-- header -->
      <header class="header">
        <h1>todos</h1>
        <input
          class="new-todo"
          autofocus
          autocomplete="off"
          placeholder="What needs to be done?"
          @keyup.enter="addTodo"
        >
      </header>

      <!-- section -->
      <section
        class="main"
      >
        <input
          class="toggle-all"
          id="toggle-all"
          type="checkbox"
          :checked='allChecked'
          @change="toggleAll(!allChecked)"
        >
        <label for="toggle-all"></label>
        <ul class="todo-list">
          <TodoItem
            name="Todo"
            v-for="(todo,index) in filterTodo"
            :key="index"
            :todo='todo'
          />
        </ul>
      </section>

      <!-- footer -->
      <footer
        class="footer"
      >
        <span class="todo-count">
          <strong>{{remaining}}</strong>
          {{remaining | pluralize('item')}} left
        </span>
        <ul class="filters">
            <li
                v-for="(v,i) in filters"
                :key="i"
            >
                <a
                :href="'#/'+i"
                :class="{selected: visibility === i}"
                @click="visibility = i"
                >{{ i | capitalize }}</a>
            </li>
        </ul>
        <button
          class="clear-completed"
           v-show="todos.length > remaining"
          @click="clearCompleted"
        >
          Clear completed
        </button>
      </footer>
    </section>
    </div>
</template>

<script>
import TodoItem from "./TodoItem";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      visibility: "all",
      filters: {
        all: todos => todos,
        active: todos => todos.filter(todo => !todo.done),
        completed: todos => todos.filter(todo => todo.done)
      }
    };
  },
  methods: {
    ...mapActions(["toggleAll", "clearCompleted"]),
    addTodo(e) {
      let text = e.target.value;
      if (text.trim()) {
        this.$store.dispatch("addTodo", text);
      }
      e.target.value = "";
    }
  },
  computed: {
    todos() {
      return this.$store.state.todos;
    },
    remaining() {
      return this.$store.state.todos.filter(todo => !todo.done).length;
    },
    allChecked() {
      return this.todos.every(todo => todo.done);
    },
    filterTodo() {
      return this.filters[this.visibility](this.todos);
    }
  },
  filters: {
    //   item后面加s
    pluralize: (n, v) => (n > 1 ? v + "s" : v),
    capitalize: v => v.charAt(0).toUpperCase() + v.slice(1)
  },
  components: {
    TodoItem
  }
};
</script>
<style src="../css/main.css"></style>
<style scoped>
</style>